package SSF.OS.NetFlow.Util;

import SSF.Util.Streams.*;
import SSF.OS.NetFlow.*;
import java.util.*;
import java.io.*;

/**
 * Test driver of IpFlowReporter.
 * Small utility that prints out the content of a netflow data file.
 * <BR>
 * <B>usage: JAVA Report &lt;filename> &lt;stream name></B>
 */
public class IpFlowSortor extends BasicPlayer
{
    Vector recordVec = new Vector(200);

    public IpFlowSortor(String streamID)
    {
	super(streamID);
    }

    /**
     * Grab an IpFlowCollector record and insert it into a vector
     * @param tid type ID or the record
     * @param sid ID corresponding to source NHI address
     * @param time timestamp when it's dumped
     * @param buf byte array storing the data
     * @param offset where in the byte array to start
     * @param length how long are the data in the array
     */
    public int receive (int tid, int sid, double time, 
			byte[] buf, int offset, int length)
    {
	IpNetFlow flow;
	//System.err.println(buf.length + " " +offset+ " " + length);
	if (tid == getRecordTypeCode("SSF.OS.NetFlow")) {
	    flow = new IpNetFlow();
	    flow.readFromBytes(buf, length);
	    recordVec.add(flow);
	    return 0;
	}
	else return super.receive(tid, sid, time, buf, offset, length);
    }

    /**
     * read in the records, sort them according to "First" field and print out.
     */
    public static void main(String args[])
    {
	IpFlowSortor ifr = null;
	if (args.length < 2) {
	    System.err.println("usage: JAVA IpFlowSortor <filename> <stream name>");
	    return;
	}

	ifr = new IpFlowSortor(args[1]); //stream name given to create Reporter
	FlowComparator comp = new FlowComparator();
	try {
	    ifr.connectRead(args[0]);  //Report
	    // now all the flow records are in the vector
	    Object[] iArray = ifr.recordVec.toArray();
	    Arrays.sort(iArray, comp);

	    for (int i=0; i<iArray.length; i++)
		System.out.println(((IpNetFlow)(iArray[i])).toString());
	}
	catch (streamException strex) {
	    System.err.println(strex.getMessage());
	    System.exit(1);
	}
    }
}
